<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #result{
            width: 200px;
            height: 200px;
            border: solid 2px purple;
        }
    </style>
</head>
<body>
    <button>发送请求</button>
    <div id="result"></div>

    
    <script>

        let btn = document.getElementsByTagName("button")[0]

        let display = document.getElementById("result")

        btn.onclick = function(){
            const xhr = new XMLHttpRequest();

            //设置请求超时时间为2s
            xhr.timeout = 2000   //2s没有响应，请求会cancle
            //设置请求超时响应方法
            xhr.ontimeout = function(){
                alert("请求超时，请稍后重试~")
            }
            //网络异常问题
            xhr.onerror = function(){
                alert("网络出现问题，请稍后重试~")
            }



            xhr.open('GET','http://localhost:8000/delay')

            xhr.send()

            xhr.onreadystatechange = function(){
                if(xhr.readyState == 4){
                    if(xhr.status <=200 && xhr.status <300){
                        display.innerHTML = xhr.response
                    }
                }
            }
        }






    </script>
</body>
</html>